<template lang="pug">
.list
  el-button(type="primary" size="small" @click="add") 添加材料
  el-button(name="primary" size="small" @click="seeDraft") 草稿箱
  .index-header
    .index-tabs
      .tab-item(:class="{ 'active' : tabActive === item.keyValue }" v-for="item in tabs" @click="changeTab(item)") {{item.label}} ({{item.num}})
    .index-filter
      header-filter(:filter="filter")
  .index-table
    .index-table-handles
      el-button(size="small" name="primary" @click="batchDel") 删除
    .index-table-body
      el-table(
        :header-cell-style="{ background: '#F3F3F3', fontSize: '14px', color: '#363636' }"
        style="width: 100%"
        :data="list"
        v-loading="loading"
        @selection-change="changeSelection"
        empty-text="未找到符合条件的内容"
      )
        el-table-column(type="selection" width="55" align="center")
        el-table-column(label="材料图片" align="center")
          template(slot-scope="scope")
            .table-item
              .table-item-img
                img(:src="scope.row.pictureImg")
        el-table-column(label="材料信息" prop="materialName" min-width="120")
          template(slot-scope="scope")
            .table-item
              .table-item-value {{scope.row.materialName}}
              .table-item-value(v-if="scope.row.brandName") 品牌：{{scope.row.brandName}}
        el-table-column(label="市场价格" min-width="120")
          template(slot-scope="scope")
            .table-item {{scope.row.lowPrice === scope.row.highPrice ? '￥' + scope.row.lowPrice : '￥' + scope.row.lowPrice + ' ~￥' + scope.row.highPrice}}
        //- el-table-column(label="成交价格" min-width="120")
          template(slot-scope="scope")
            .table-item ￥{{scope.row.minFinalPrice}}~￥{{scope.row.maxFinalPrice}}
        el-table-column(label="标签" prop="status")
          template(slot-scope="scope")
            .table-item-switch.flex
              .switch-label 上架：
              .switch-bd
                el-switch(v-model="scope.row.isOnSales" :disabled="scope.row.status !== '审核通过'" @change="putOnOrOff(scope.row)")
            .table-item-switch.flex
              .switch-label 新品：
              .switch-bd
                el-switch(v-model="scope.row.isNew" :disabled="scope.row.status !== '审核通过'" @change="changeNewStatus(scope.row)")
        el-table-column(label="分类" prop="classificationName" min-width="120")
        el-table-column(label="SKU库存" prop="entriesAmount" align="center")
          template(slot-scope="scope")
            .table-item
              .iconfont.el-icon-edit-outline(@click="editSku(scope.row)")
        el-table-column(label="浏览数" prop="viewAmount")
        el-table-column(label="审核状态" prop="status")
          template(slot-scope="scope")
            .table-item {{scope.row.status}}
            .table-item-handle(@click="seeAuditDetail(scope.row)") 审核详情
        el-table-column(label="操作" align="center" min-width="200")
          template(slot-scope="scope")
            .table-handles
              .table-handle-item(@click="seeDetail(scope.row)") 查看
              .table-handle-item(@click="editMaterial(scope.row)") 编辑
              .table-handle-item(@click="seeRecord(scope.row)") 日志
              .table-handle-item(@click="delMaterial(scope.row)") 删除
    .index-pagination
      .pagination-total 共 {{total}} 条
      .pagination-sizes 10 条/页
      el-pagination(
        background
        layout="prev, pager, next, jumper"
        :total="total"
        :page-size="pageSize"
        :current-page="page"
        @current-change="currentChange"
      )
  audit-record-modal(:show="showRecordModal" :item="currentItem" @close="closeRecordModal")
  change-sku-spec(:show="showSkuModal" :item="currentItem" @close="closeSkuModal" @save="changeSku")
  material-record-modal(:show="showMaterialRecord" :item="currentItem" @close="closeMaterialRecord")
</template>

<script>
import { getMaterialList, getStyles, loadSupplierBrands, getMaterialCategory, putOnOrOff, setUpdateNew, deleteMaterial, getStatusTotal } from 'api'
import headerFilter from '@/components/headerFilter'
import auditRecordModal from './module/auditRecordModal'
import changeSkuSpec from './module/changeSkuSpec'
import materialRecordModal from './module/materialRecordModal'
export default {
  name: 'materialList',
  components: {
    headerFilter,
    auditRecordModal,
    changeSkuSpec,
    materialRecordModal
  },
  data () {
    return {
      tabActive: '',
      tabs: [
        { label: '全部材料', key: '', value: '', keyValue: '', num: 0 },
        { label: '已上架', key: 'isOnSales', value: 1, keyValue: 1, num: 0 },
        { label: '未上架', key: 'isOnSales', value: 0, keyValue: 2, num: 0 },
        { label: '待审核', key: 'status', value: 1, keyValue: 4, num: 0 },
        { label: '审核不通过', key: 'status', value: 3, keyValue: 6, num: 0 }
      ],
      filter: [
        [
          {
            name: '材料名称：',
            type: 'default',
            key: 'materialName',
            materialName: '',
          },
          {
            name: '材料分类：',
            type: 'treble',
            key: 'category',
            category: [
              { key: 'first_cate', first_cate: '', optLabel: 'title', optValue: 'id', options: [], labelShow: false, handle: this.changeCate },
              { key: 'secend_cate', secend_cate: '', optLabel: 'title', optValue: 'id', options: [], labelShow: false, handle: this.changeCate },
              { key: 'three_cate', three_cate: '', optLabel: 'title', optValue: 'id', options: [], labelShow: false, handle: this.changeCate },
              { key: 'four_cate', four_cate: '', optLabel: 'title', optValue: 'id', options: [], labelShow: false, handle: this.changeCate }
            ]
          }
        ],
        [
          {
            name: '材料品牌：',
            type: 'filterable',
            key: 'brandId',
            handle: '',
            brandId: '',
            optLabel: 'name',
            optValue: 'brandId',
            options: []
          },
          {
            type: 'handle',
            buttons: [
              { name: 'primary', label: '查询', handle: this.search },
              { label: '重置', handle: this.reset }
            ]
          }
        ]
      ],
      showRecordModal: false,
      showSkuModal: false,
      showMaterialRecord: false,
      currentItem: {},
      list: [],
      loading: false,
      total: 0,
      page: 1,
      pageSize: 10,
      styles: [],
      brands: [],
      categories: [],
      secends: [],
      threes: [],
      fours: [],
      cat_id: '',
      selection: []
    }
  },
  methods: {
    changeTab (item) {
      this.tabActive = item.keyValue
      let query = { ...this.$route.query, currentPage: 1 }
      delete query.isOnSales
      delete query.status
      if (item.value !== '') query[item.key] = item.value
      // let filter = this.tabs.find(row => row.value === item)
      // delete query.isFinish
      // if (query.hasFeedback) delete query.hasFeedback
      // if (filter.label !== '全部') query[filter.key] = filter.value
      this.$router.replace({ name: this.$route.name, query: { ...query, tm: new Date().getTime() } })
    },
    changeSelection (selection) {
      this.selection = selection
    },
    batchDel () {
      if (!this.selection.length) {
        this.$message.error('请先选择要删除的材料！')
        return
      }
      this.$confirm('是否要删除所选材料？', '材料删除').then(async () => {
        try {
          let ids = this.selection.map(item => item.materialId)
          await this.$axios.post(deleteMaterial, { content: { materialList: ids.join(',') } })
          this.$message.success('删除成功！')
          this.getList()
        } catch (err) {
          console.log(err)
          this.$message.error(err.message || err.ResultSet.errors)
        }
      })
    },
    seeDraft () {
      this.$router.push({ name: 'materialDraft' })
    },
    editSku (row) {
      this.currentItem = row
      this.showSkuModal = true
    },
    changeSku () {
      this.getList()
      this.currentItem = {}
      this.showSkuModal = false
    },
    closeSkuModal () {
      this.currentItem = {}
      this.showSkuModal = false
    },
    seeAuditDetail (row) {
      this.currentItem = row
      this.showRecordModal = true
    },
    closeRecordModal () {
      this.currentItem = {}
      this.showRecordModal = false
    },
    seeDetail (row) {
      this.$router.push({ name: 'goodsDetail', params: { id: row.materialId } })
    },
    seeRecord (row) {
      this.currentItem = row
      this.showMaterialRecord = true
    },
    closeMaterialRecord () {
      this.currentItem = {}
      this.showMaterialRecord = false
    },
    editMaterial (row) {
      this.$router.push({ name: 'upload', params: { id: row.materialId } })
    },
    add () {
      this.$router.push({ name: 'upload' })
    },
    async putOnOrOff (row) {
      try {
        await this.$axios.post(putOnOrOff, { content: { materialId: row.materialId } })
        this.$message.success('操作成功！')
        this.getList()
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    async changeNewStatus (row) {
      try {
        await this.$axios.post(setUpdateNew, { content: { id: row.materialId, isNew: row.isNew } })
        this.$message.success('操作成功！')
        this.getList()
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    delMaterial (row) {
      this.$confirm('确定要删除该材料吗？', '提示').then(async () => {
        try {
          await this.$axios.post(deleteMaterial, { content: { materialList: row.materialId } })
          this.$message.success('删除成功！')
          this.getList()
        } catch (err) {
          console.log(err)
          this.$message.error(err.message || err.ResultSet.errors)
        }
      })
    },
    search () {
      let query = {}
      this.filter.map(row => row.map(v => {
        if (v.key === 'category') {
          v[v.key].forEach(item => {
            if (item[item.key] !== '') query[item.key] = item[item.key]
          })
        } else {
          if (v[v.key]) query[v.key] = v[v.key]
        }
      }))
      Object.keys(query).forEach(v => {
        if (!query[v]) delete query[v]
      })
      if (this.cat_id !== '') query.category = this.cat_id
      else {
        if (this.$route.query.category) query.category = this.$route.query.category
      }
      let tabItem = this.tabs.find(item => item.keyValue === this.tabActive)
      delete query.isOnSales
      delete query.status
      if (tabItem.value !== '') query[tabItem.key] = tabItem.value
      this.$router.replace({ name: this.$route.name, query: { ...query, tm: new Date().getTime() } })
    },
    reset () {
      let query = {}
      let tabItem = this.tabs.find(item => item.keyValue === this.tabActive)
      delete query.isOnSales
      delete query.status
      if (tabItem.value !== '') query[tabItem.key] = tabItem.value
      this.$router.replace({ name: this.$route.name, query: { ...query } })
    },
    // 商品分类初始化
    async initCateList () {
      try {
        const { ResultSet } = await this.$axios.post(getMaterialCategory)
        this.categories = ResultSet.userData.roots
        if (this.$route.query.first_cate) {
          let row = this.categories.find(item => item.id === parseInt(this.$route.query.first_cate))
          this.secends = row.children || []
        }
        if (this.$route.query.secend_cate) {
          let row = this.secends.find(item => item.id === parseInt(this.$route.query.secend_cate))
          this.threes = row.children || []
        }
        if (this.$route.query.three_cate) {
          let row = this.threes.find(item => item.id === parseInt(this.$route.query.three_cate))
          this.fours = row.children || []
        }
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    async initFilter () {
      try {
        await this.initCateList()
        this.filter.forEach(row => row.forEach(v => {
          if (v.key === 'styleId') v.options = this.styles
          if (v.key === 'brandId') v.options = this.brands
          if (v.key === 'category') {
            v[v.key].forEach(cate => {
              cate[cate.key] = !isNaN(Number(this.$route.query[cate.key])) ? Number(this.$route.query[cate.key]) : ''
            })
            v[v.key][0].options = this.categories
            v[v.key][1].options = this.secends
            v[v.key][2].options = this.threes
            v[v.key][3].options = this.fours
          } else if (v.key === 'styleId') {
            v[v.key] = Number(this.$route.query[v.key]) || ''
          }  else {
            v[v.key] = this.$route.query[v.key] || ''
          }
        }))
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    // 商品分类选择分类
    async changeCate (col) {
      try {
        let index = col.options.findIndex(item => item.id === col[col.key])
        let options = col.options[index].children || []
        this.filter.forEach(row => row.forEach(item => {
          if (item.key === 'category') {
            let cate = item[item.key]
            if (col.key === 'first_cate') {
              cate[1].options = options
              cate[1].secend_cate = ''
              cate[2].options = []
              cate[2].three_cate = ''
              cate[3].options = []
              cate[3].four_cate = ''
            } else if (col.key === 'secend_cate') {
              cate[2].options = options
              cate[2].three_cate = ''
              cate[3].options = []
              cate[3].four_cate = ''
            } else if (col.key === 'three_cate') {
              cate[3].options = options
              cate[3].four_cate = ''
            }
          }
        }))
        this.cat_id = col[col.key]
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    async getStyles () {
      try {
        const { ResultSet } = await this.$axios.post(getStyles)
        this.styles = ResultSet.userData.businessStyles
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    async getBrands () {
      try {
        const { ResultSet } = await this.$axios.post(loadSupplierBrands, { content: { reviewStatus: 2 } })
        this.brands = ResultSet.userData.brandList
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    currentChange (page) {
      this.$router.replace({ name: this.$route.name, query: { ...this.$route.query, currentPage: page, tm: new Date().getTime() } })
    },
    async getList () {
      try {
        const { ResultSet } = await this.$axios.post(getMaterialList, { content: { ...this.$route.query, currentPage: this.$route.query.currentPage || 1, pageLines: this.$route.query.pageSize || 10 } })
        this.getStatusTotal()
        if (this.$route.query.isOnSales !== '' && this.$route.query.isOnSales !== undefined) {
          let item = this.tabs.find(item => item.key === 'isOnSales' && item.value === parseInt(this.$route.query.isOnSales))
          this.tabActive = item.keyValue
        }
        if (this.$route.query.status !== '' && this.$route.query.status !== undefined) {
          let item = this.tabs.find(item => item.key === 'status' && item.value === parseInt(this.$route.query.status))
          this.tabActive = item.keyValue
        }
        this.page = Number(this.$route.query.currentPage) || 1
        this.list = ResultSet.userData.materialList
        this.total = ResultSet.recordNumber
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    async getStatusTotal () {
      try {
        const { ResultSet } = await this.$axios.post(getStatusTotal)
        this.tabs.forEach(item => {
          let row = ResultSet.userData.statusTotal.find(row => item.label === row.status)
          if (row) item.num = row.total
        })
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    }
  },
  beforeRouteEnter (to, from, next) {
    next(async vm => {
      await vm.getStyles()
      await vm.getBrands()
      vm.getList()
      vm.initFilter()
    })
  },
  beforeRouteUpdate (to, from, next) {
    next()
    this.getList()
    this.initFilter()
  }
} 
</script>

<style lang="scss" scoped>
.list {
  padding: 0 32px 16px;
  height: 100%;
}
.index-header {
  margin-top: 16px;
  padding: 32px 24px;
  background: #ffffff;
  border-radius: 4px;
}
.index-tabs {
  display: flex;
  align-items: center;
  .tab-item {
    // width: 88px;
    padding: 0 15px;
    height: 32px;
    line-height: 32px;
    text-align: center;
    font-size: 14px;
    color: #FF2E42;
    border: 1px solid #FF2E42;
    border-right: none;
    background: #fff;
    cursor: pointer;
    &:first-child {
      border-radius: 4px 0px 0px 4px;
    }
    &:last-child {
      border-radius: 0px 4px 4px 0px;
      border-right: 1px solid #FF2E42;
    }
    &.active {
      background: #FF2E42;
      color: #fff;
    }
  }
}
.index-filter {
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid #CBCBCB;
}
.filter-row {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  &:last-child {
    margin-bottom: 0;
  }
}
.filter-col {
  min-width: 320px;
  margin-right: 30px;
  display: flex;
  align-items: center;
  .filter-col-label {
    width: 100px;
    padding-right: 10px;
    text-align: right;
    font-size: 14px;
    color: #363636;
  }
  .filter-col-bd {
    width: 220px;
    .el-select {
      width: 100%;
    }
    .el-input {
      width: 100%;
    }
    &.filter-col-handle {
      text-align: right;
    }
  }
}
.index-table {
  margin-top: 16px;
  padding: 24px;
  background: #fff;
  border-radius: 4px;
}
.index-table-body {
  margin-top: 16px;
}
.index-pagination {
  margin-top: 24px;
  text-align: right;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  font-size: 14px;
  color: #7A7A7A;
  .pagination-total {
    margin-right: 10px;
  }
  .pagination-sizes {
    margin-right: 10px;
  }
}
.table-handles {
  display: flex;
  justify-content: center;
  .table-handle-item {
    padding: 0 10px;
    white-space: nowrap;
    line-height: 1;
    cursor: pointer;
    border-right: 1px solid #CBCBCB;
    color: #FF2E42;
    &:first-child {
      padding-left: 0;
    }
    &:last-child {
      border-right: none;
    }
  }
}
.table-item {
  .table-item-img {
    width: 80px;
  }
  .el-icon-edit-outline {
    color: #FF2E42;
    font-size: 18px;
    cursor: pointer;
  }
}
.table-item-switch {
  margin: 5px 0;
}
.flex {
  display: flex;
  align-items: center;
}
.table-item-handle {
  cursor: pointer;
  color: #FF2E42;
}
</style>
